package com.ciwong.epaper.modules.me.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.LogOutUtil;
import com.ciwong.epaper.util.download.DownLoadDB;
import com.ciwong.epaper.widget.NewLoginDialog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.FileUtils;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseSystem;
import com.ciwong.mobilelib.utils.CWUpdate;
import com.ciwong.mobilelib.utils.EAction;
import com.ciwong.mobilelib.utils.ThreadTask;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.BottomMenuDialog;
import com.ciwong.mobilelib.widget.CWDialog;
import com.ciwong.mobilelib.widget.switchbutton.SwitchButton;

import java.io.File;
import java.util.ArrayList;

import static com.ciwong.epaper.modules.me.ui.MeFragment.REQUEST_CODE_TO_MODIFY_USER_INFO;

/**
 * Created by pla-wyliu on 2015/7/25. 设置activity
 */
public class SettingActivity extends BaseActivity {

    private ViewGroup lyAbout, lyAutoDown, lyVersionUpdate, lyOnlineService;
    private ViewGroup setting_my_info, setting_net_test, setting_written_off, privacy_protection_statement;
    private Button btnLogout;
    private BottomMenuDialog bottomMenuDialog;
    private SwitchButton mCbAutoDown;
    private TextView mVersionTv;

    /**
     * 进度条
     */
    private ProgressBar mProUpdate;

//    private String rootPath = ESystem.getPackagesPath(SettingActivity.this);

//    private File packagesFile = new File(rootPath);

    private float fileSize;

    private static final int M_M = 1024 * 1024;

    public static final int SETING_BACK_RETURN = 1;
    public static final int REQUEST_BIND_CODE = 10001;


    private ImageView img_update_tips;

    private ViewOnClickListener mViewOnClickListener = new ViewOnClickListener() {
        @Override
        public void avertRepeatOnClick(View v) {
            int id = v.getId();
            if (id == R.id.ly_version_update) {
                upData();
            } else if (id == R.id.lylogout) {
                exitDialog();
            } else if (id == R.id.ly_about) {
                MeJumpManager.jumpToAbout(SettingActivity.this);
            } else if (id == R.id.setting_online_service_rl) {
                MeJumpManager.jumpToOnlineService(SettingActivity.this,
                        R.string.go_back, EConstants.ONLINE_SERVICE,
                        getString(R.string.online_service));
            } else if (id == R.id.iv_setting_assess) {
                v.setSelected(!v.isSelected());
                CWSys.setSharedBoolean(
                        EConstants.SHARE_KEY_IS_ASSESS
                                + getUserInfoBase().getUserId(),
                        v.isSelected());

            } else if (id == R.id.iv_setting_listen_speak) {
                v.setSelected(!v.isSelected());
                CWSys.setSharedBoolean(
                        EConstants.SHARE_KEY_IS_PLAY_STEM_AUDIO
                                + getUserInfoBase().getUserId(),
                        v.isSelected());

            } else if (id == R.id.setting_my_info) {
                if (EConstants.IS_YOUKE) {
                    NewLoginDialog newLoginDialog = new NewLoginDialog(SettingActivity.this);
                    newLoginDialog.showLoginDialog();

                } else {
                    v.setSelected(!v.isSelected());
                    MeJumpManager.jumpToMyInfo(SettingActivity.this, R.string.go_back, REQUEST_CODE_TO_MODIFY_USER_INFO);
                }
            } else if (id == R.id.setting_net_test) {
                if (EConstants.IS_YOUKE) {
                    NewLoginDialog newLoginDialog = new NewLoginDialog(SettingActivity.this);
                    newLoginDialog.showLoginDialog();

                } else {
                    //测试网络环境
                    MeJumpManager.jumpToNetAct(SettingActivity.this, R.string.go_back);
                }
            } else if (id == R.id.setting_written_off) {
                //注销账号
                MeJumpManager.jumpWrittenOffActivity(R.string.go_back, SettingActivity.this, getString(R.string.written_off_url), getString(R.string.written_off));
            } else if (id == R.id.privacy_protection_statement) {
                MeJumpManager.jumpToAreementCancel(SettingActivity.this, R.string.go_back,
                        getString(R.string.agreement_cancel_url), getString(R.string.agreement_cancel_name));
            }
        }
    };

    @Override
    protected int setView() {
        return R.layout.activity_setting;
    }

    @Override
    protected void findViews() {
        lyAbout = findViewById(R.id.ly_about);
        setting_my_info = findViewById(R.id.setting_my_info);
        setting_net_test = findViewById(R.id.setting_net_test);
        setting_written_off = findViewById(R.id.setting_written_off);
        btnLogout = findViewById(R.id.lylogout);
        lyAutoDown = findViewById(R.id.ly_auto_down_res);
        lyVersionUpdate = findViewById(R.id.ly_version_update);
        lyOnlineService = findViewById(
                R.id.setting_online_service_rl);
        mProUpdate = findViewById(R.id.set_update_pro);
        privacy_protection_statement = findViewById(R.id.privacy_protection_statement);
        mCbAutoDown = findViewById(R.id.sb_auto_down_res);
        mVersionTv = findViewById(R.id.activity_setting_version);
        img_update_tips = findViewById(R.id.img_update_tips);

    }

    @Override
    protected void initEvent() {
        lyAbout.setOnClickListener(mViewOnClickListener);
        btnLogout.setOnClickListener(mViewOnClickListener);
        lyVersionUpdate.setOnClickListener(mViewOnClickListener);

        lyOnlineService.setOnClickListener(mViewOnClickListener);

        setting_my_info.setOnClickListener(mViewOnClickListener);
        setting_net_test.setOnClickListener(mViewOnClickListener);
        setting_written_off.setOnClickListener(mViewOnClickListener);
        privacy_protection_statement.setOnClickListener(mViewOnClickListener);

        setGoBackListener(new GoBackListener() {
            @Override
            public void goBack() {
                onBackPressed();
            }
        });
    }

    @Override
    protected void init() {
        setTitleText(R.string.setting);
        setBottomMenuDialog();
        try {
            mVersionTv.setText(getPackageManager()
                    .getPackageInfo(getPackageName(), 0).versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        long versionCode = CWSys.getSharedInt(CWUpdate.APK_UPDATE_SERVICE_VERSION_CODE, -1);
        int sysVersionCode = BaseSystem.getSystemVersionCode(getApplicationContext());

        if (versionCode > 0 && sysVersionCode < versionCode) {
            img_update_tips.setVisibility(View.VISIBLE);
        } else {
            img_update_tips.setVisibility(View.INVISIBLE);
        }


    }

    @Override
    protected void loadData() {
//        setFileSize();
    }

    private void setBottomMenuDialog() {
        bottomMenuDialog = new BottomMenuDialog(this);
        bottomMenuDialog
                .setBtnTextColor(getResources().getColor(R.color.green));
        bottomMenuDialog
                .setLastBtnTextColor(getResources().getColor(R.color.gray));

        ArrayList<String> str = new ArrayList<String>();

        str.add(getResources().getString(R.string.sure_clean_cache));
        str.add(getResources().getString(android.R.string.cancel));
        bottomMenuDialog.setMenuTextList(str);

        ArrayList<View.OnClickListener> listeners = new ArrayList<View.OnClickListener>();

        CleanCacheListener cleanCacheListener = new CleanCacheListener();
        CancleListener cancleListener = new CancleListener();

        listeners.add(cleanCacheListener);
        listeners.add(cancleListener);

        bottomMenuDialog.setMenuOnClickListeners(listeners);

    }

    class CleanCacheListener extends ViewOnClickListener {

        @Override
        public void avertRepeatOnClick(View v) {
            bottomMenuDialog.dismiss();
            // 清除缓存删除数据库数据
            showMiddleProgressBar(getTitleText());
            ThreadTask.getInstance().executorDBThread(new Runnable() {
                @Override
                public void run() {
                    DownLoadDB.cleanData();
                    FileUtils.delete(ESystem.getPackagesPath(SettingActivity.this));

                    SettingActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                            mFileSizeTv.setText("0.0M");
                            hideMiddleProgressBar();
                            //通知首页我的作业刷新状态
                            sendBroadcast(new Intent(EpaperConstant.ACTION_PACKAGE_DELETE));
                        }
                    });
                }
            }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);


        }
    }

    class CancleListener extends ViewOnClickListener {

        @Override
        public void avertRepeatOnClick(View v) {
            bottomMenuDialog.dismiss();
        }
    }

    /**
     * 更新APK
     */
    private void upData() {

        if (!NetworkUtils.isOnline()) {
            ToastUtil.INSTANCE.toastCenterNoNetError();
            return;
        }

        if (mProUpdate.getVisibility() != View.VISIBLE) {
            mProUpdate.setVisibility(View.VISIBLE);

            CWUpdate update = new CWUpdate(this, EAction.getUpgradeUrl(),
                    new CWUpdate.Callback() {

                        @Override
                        public void excuteSelfMethod(Object... obj) {
                            mProUpdate.setVisibility(View.GONE);
                            if (obj != null && obj.length > 0) {
                                if (obj[0].equals(CWUpdate.UPDATE_FLAG_ERROR)) {
                                    showToastError(
                                            R.string.download_apk_failed);
                                } else if (obj[0]
                                        .equals(CWUpdate.UPDATE_FLAG_ISLATEST)) {
//                                    showToastSuccess(R.string.alreadylatest);
                                    ToastUtil.INSTANCE.toastCenter(EApplication.getInstance(), R.string.alreadylatest, R.mipmap.ic_new_version);
                                } else if (obj[0]
                                        .equals(CWUpdate.UPDATE_BACKGROUND)) {
                                    mProUpdate.setVisibility(View.VISIBLE);
                                } else if (obj[0].equals(CWUpdate.COMPLETE)) {
                                    mProUpdate.setVisibility(View.GONE);
                                }
                            }
                        }
                    });
            update.excute(false);
        }
    }

    /**
     * 退出登录
     */
    private void exitDialog() {

        final CWDialog dialog = new CWDialog(this, false, false);
        dialog.setTitle(R.string.tips);
        dialog.setTitleTextColor(Color.BLACK);
        dialog.setMessage("退出登录？", 16, Color.BLACK);
        dialog.setPositiveButton(android.R.string.ok,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface interDialog,
                                        int which) {
                        showMiddleProgressBar(getString(R.string.setting));
                        dialog.setMessage(getString(R.string.logout));
                        executeOtherThread(new Runnable() {
                            @Override
                            public void run() {
                                interDialog.dismiss();
                                setResult(RESULT_OK);
                                LogOutUtil.logOut(SettingActivity.this);
                                finish();
                            }
                        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);

                    }
                });
        dialog.setNegativeButton(android.R.string.cancel,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        dialog.show();


    }

//    private void setFileSize() {
//        ThreadTask.getInstance().executorOtherThread(new Runnable() {
//            @Override
//            public void run() {
//
//
//                fileSize = FileUtil.getFolderSize(packagesFile) / M_M;
//
//                DownloadCenter downloadCenter;
//                downloadCenter = DownloadCenter.getInstances(SettingActivity.this.getApplicationContext());
//                List<LeDownloadInfo> downloadInfoList = downloadCenter.getDownloadInfoList();
//
//                float videoFileSize=0;
//
//                for (int i=0;i<downloadInfoList.size();i++) {
//                    videoFileSize=videoFileSize+downloadInfoList.get(i).getFileLength();
//                }
//                if (videoFileSize > 0) {
//                    videoFileSize=videoFileSize/ M_M;
//                }
//
//                fileSize=fileSize+videoFileSize;
//
//                SettingActivity.this.runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        String size = String.format("%.2f", fileSize);
//                        mFileSizeTv.setText(size + "MB");
//                    }
//                });
//
//            }
//        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
//    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case EpaperConstant.REQUEST_CODE_WIPE_CACHE:
//                    setFileSize();
                    break;
            }
        }

    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_OK);
//        setResult(RESULT_OK);
        finish();
    }


}
